package com.dk.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.dk.config.AlipayConfig;
import com.dk.result.Result;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("alipay")
public class AlipayController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("alipayTradePagePay")
    @ApiOperation(value = "支付（支付宝）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "out_trade_no", value = "商户订单号", required = true, type = "path"),
            @ApiImplicitParam(name = "orderName", value = "订单名称", required = true, type = "path"),
            @ApiImplicitParam(name = "money", value = "付款金额（定金2000）", required = true, type = "path"),
            @ApiImplicitParam(name = "carsDesc", value = "车辆描述", required = true, type = "path")
    })
    public String alipayTradePagePay(String outTradeNo, String orderName, String money, String carsDesc) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //付款金额，必填
        //String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
        //订单名称，必填
        //String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"),"UTF-8");
        //商品描述，可空
        //String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"total_amount\":\"" + money + "\","
                + "\"subject\":\"" + orderName + "\","
                + "\"body\":\"" + carsDesc + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //输出
        return result;
    }

    /**
     * 退款
     *
     * @param out_trade_no   商户订单号         //商户网站订单系统中唯一订单号
     * @param trade_no       支付宝交易号           //该金额不能大于订单金额，必填
     * @param refund_amount  退款的金额
     * @param refund_reason  退款的原因
     * @param out_request_no 标识一次退款请求   //同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
     * @return
     */
    @PostMapping("alipayTradeRefund")
    @ApiOperation(value = "退款（支付宝）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "out_trade_no", value = "商户订单号", required = true, type = "path"),
            @ApiImplicitParam(name = "trade_no", value = "支付宝交易号", required = true, type = "path"),
            @ApiImplicitParam(name = "refund_amount", value = "退款的金额（定金2000）", required = true, type = "path"),
            @ApiImplicitParam(name = "refund_reason", value = "退款的原因", required = true, type = "path"),
            @ApiImplicitParam(name = "out_request_no", value = "标识一次退款请求", required = true, type = "path")
    })
    public Result alipayTradeRefund(String out_trade_no, String trade_no, String refund_amount, String refund_reason, String out_request_no) {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
                AlipayConfig.gatewayUrl,
                AlipayConfig.app_id,
                AlipayConfig.merchant_private_key,
                "json",
                AlipayConfig.charset,
                AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type
        );

        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        alipayRequest.setBizContent("{"
                + "\"out_trade_no\":\"" + out_trade_no
                + "\","
                + "\"trade_no\":\"" + trade_no
                + "\","
                + "\"refund_amount\":\"" + refund_amount
                + "\","
                + "\"refund_reason\":\"" + refund_reason
                + "\","
                + "\"out_request_no\":\"" + out_request_no + "\"}"
        );

        //请求
        try {
            String result = alipayClient.execute(alipayRequest).getBody();

            System.out.println(result);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        //将退款请求号存到redis中
        stringRedisTemplate.opsForValue().set("old_car_refund_" + out_trade_no, out_trade_no);

        return Result.OK();
    }

}